package com.bw.contorller;

import com.bw.entity.PinPai;
import com.bw.entity.Spu;
import com.bw.entity.Type;
import com.bw.service.SpuService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Controller
public class SpuContorller {
  @Autowired
  SpuService spuService;

  @RequestMapping("toindex")
    public String toIndex(){
      return "index";
  }

  @RequestMapping("list")
    public String List(Spu spu, Model model,@RequestParam(defaultValue = "1") Integer pageNum){
      PageInfo<Spu> info=spuService.list(spu,pageNum);
      model.addAttribute("spu",spu);
      model.addAttribute("pg",info);
      return "list";
  }

  @ResponseBody
  @RequestMapping("selectBypid")
  public List<PinPai> selectBypid(){
    List<PinPai> list=spuService.selectBypid();

    return list;
  }

  @RequestMapping("toadd")
  public String toAdd(Spu spu,Model model) {
    model.addAttribute("spu",spu);
    return "add";
  }

  @RequestMapping("add")
  public String Add(Spu spu){
    int i=spuService.toInsert(spu);
    if(i>0){
      return "redirect:toindex";
    }
    return "add";
  }

  @ResponseBody
  @RequestMapping("selectTid")
  public List<Type> selectTid(Integer tid1){
    List<Type> list=spuService.selectTid(tid1);
    return list;
  }

  @ResponseBody
  @RequestMapping("selectPid")
  public List<PinPai> selectPid(Integer tid1){
    List<PinPai> list=spuService.selectPid(tid1);
    return list;
  }

  @ResponseBody
  @RequestMapping("getpicurl")
  public String getPicurl(MultipartFile file) throws IOException {
      String path="d:/pic";
    String originalFilename = file.getOriginalFilename();
    String s = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
    File file1 = new File(path, s);
    file.transferTo(file1);
    return "/pic/"+s;
  }

  //修改
  @RequestMapping("selectByid")
  public String selectByid(Integer ids,Model model){
    Spu spu=spuService.selectByid(ids);
    model.addAttribute("spu",spu);
    return "update";
  }

  //执行修改
  @RequestMapping("update")
  public  String toUpdate(Spu spu){
    int i=spuService.toUpdate(spu);
    if(i>0){
      return "redirect:toindex";
    }
    return "update";
  }

  @ResponseBody
  @RequestMapping("/deleteByid")
  public int deleteByid(@RequestParam("ids[]") Integer[] ids){
    int i=spuService.deleteByid(ids);
    return i;
  }
}
